/*  
 * cafe-moddialog.js
 * @Author :      PANRUSEN
 * @CreateDate :  2017年6月12日
 * Copyright (c) 2017, NRIET.　
 * TODO
 * 		模态弹窗
 */

;define(function(){
	
	'use strict';
	
	var NRIET_MODBOXS = [];
	//获取弹窗HTML
	function getNodeHtml(cfs){
		var curMsNum = dateUtil.getCurrentMs(), 
			id = cfs.id? cfs.id: 'moddialog-' + curMsNum;
		NRIET_MODBOXS.push(id);
		var wrapper = $('<div class="modal fadeInDown">');
		wrapper.attr({
			id: id,
			role: 'dialog',
			'aria-labelledby': id + '-Label',
			tabindex: '-1'
		});	
		$.each(cfs.position, function(key, v){
			wrapper.css(key, v);
		});
		var doc = $('<div class="modal-dialog" role="document">'), 
			content = $('<div class="modal-content">'),
			header = $('<div class="modal-header">'),
			body = $('<div class="modal-body">'),
			footer = $('<div class="modal-footer">');
		doc.append(content.append(header).append(body).append(footer));
		wrapper.append(doc);
		return wrapper;
	}
	//设置初始配置信息
	function setConfig(mbox, cfs){
		
		if(!mbox) return null;
		
		var $header = mbox.find('div.modal-header'),
			$content = mbox.find('div.modal-content'),
			$body = mbox.find('div.modal-body'),
			$dialog = mbox.find('div.modal-dialog'),
			$footer = mbox.find('div.modal-footer'),
			id = mbox.attr('id');
		
		function _setHeader(){
			if(cfs.closefunc){
				var close = $('<a class="close">');
				close.attr({
					'data-dismiss':'modal',
					'aria-label':'Close',
				}).data({
					'dismiss':'modal'
				}).html('&times');	
				$header.append(close);
			}
			if(cfs.title){
				var tit = $('<i>').html(cfs.title);
				$header.append(tit);
			}
		}
		
		//匹配链接地址表达式
		var reghttp = /^http:*|^https:*/;
		function _setContent(){
			var isInfo = cfs.content && cfs.type === '_info',
				isLoad = cfs.type === '_load' && cfs.url && reghttp.test(cfs.url) && cfs.ajaxType,
				isFrame = cfs.type === '_frame' && cfs.url && reghttp.test(cfs.url);
			var padding = isInfo? $.isNumeric(cfs.padding)? cfs.padding : 15 :0; 
			var ofs = TypeUtil.isNumber(padding)? padding*2 : 2;
			$dialog.css({
				width: cfs.width,
				height: cfs.height,
			});
//			if(cfs.position){
//				$dialog.css({
//					top: 'auto',
//					left: 'auto',
//					right: 'auto',
//					bottom: 'auto'
//				});
//				$.each(cfs.position, function(key, v){
//					$dialog.css(key, v);
//				});
//			}
			$content.css({
				width: cfs.width,
				height: cfs.height,
			});
			$body.empty().css({
				padding: padding,
				//width: cfs.width == "auto" ? cfs.width : 'calc(' + cfs.width + " - " + (ofs) + "px)",
				width: cfs.width == "auto" ? cfs.width : cfs.width + "px)",
				height: cfs.height == "auto" ? cfs.height : 'calc(' + cfs.height + " - " + (ofs+ (cfs.type === '_frame' ? 0 : 70)) + "px)",
//				overflow: 'hidden',
//				'overflow-x': cfs.overflow[0],
//				'overflow-y': cfs.overflow[1]
			});
			if(isInfo){
				$body.html(cfs.content);
			} else if(isLoad){
				$.ajax({ 
        			url: cfs.url, 
        			type: cfs.ajaxType,
        			dataType: "html",
        			crossDomain: true,
        			async: false,
        			context: $body, 
        			success: function(rest, textStatus, jqXHR){
        				if(jqXHR.status == 200 && textStatus == 'success'){
        					$(this).html(rest); 
        				}
        			},
        			error: function (XHR, textStatus, errorThrown) {
        				console.error(errorThrown);
        			},
        			complete: function(XHR, TS){}
        		});
			} else if(isFrame){
				var frameid = id + '_iframe'; 
				if($("iframe#" + 'frameid').length > 0) $("iframe#" + 'frameid').remove();
				var $iframe = $('<iframe>').attr({
						id : frameid,
						name : frameid,
						src : null,
						frameborder : 0,
						scrolling : "no",
						initMethod : "none"
				}).css({
					width : "100%",
					height : "100%",
					background : "#FFF"
				});
				$body.append($iframe);
				$iframe.attr('src', cfs.url);
			}
		}
		
		function _setFooter(){
			var hasFooter = cfs.buttons;
			if(hasFooter){
				$.each(cfs.buttons, function(key, btn){
					if(btn){
						var button = $('<button class="btn btn-default">');
						button.attr({
							id: btn.id,
						}).text(btn.name);
						button.on('click', function(){
							if(typeof btn.call === 'function'){
								btn.call();
							} else {
								mbox.modal('hide');
							}
						})
						$footer.append(button);
					}
				});
			} else {
				$footer.hide();
			}
		}
		
		_setHeader();
		_setContent();
		_setFooter();
		
		return mbox;
	}
	
	function _modal(mbox, cfs){
		if(!mbox) return; 
		var header = $(mbox).find('div.modal-header'),
			hasDargable = header && header.length && cfs.dragable;
		mbox.modal({
			backdrop: cfs.hasMask,
			show:false
		}).on('shown.bs.modal', function(e){
			if(hasDargable){
				$(this).find("div.modal-dialog").draggable({
					handle: '.modal-header'
				});
				$(this).css({
					overflow: 'hidden'
				});
			}
			if(typeof cfs.showCall === 'function'){
				cfs.showCall();
			}
		}).on('hidden.bs.modal', function(e){
			$(this).remove();
			if(typeof cfs.closeCall === 'function'){
				cfs.closeCall();
			}
		});
		return mbox;
	}
	 
	CafeJS.ModalBox = function(settings){
		var options = {
				/*
				 * 模态框类型，暂支持类型有：
				 * 	_info(常规内容，格式html str)
				 *  _frame(加载一外部链接URL，格式以http或https开头的外部系统链接，此链接将会在模态框中以iframe的形式被加载)
				 *  _load(加载系统内部模板URL，格式以http或https开头的内部模板URL，此链接将会以ajax形式被请求(type:get))
				*/
				type: '_info',
				id: null,
				content: 'info...',
				url: null,
				ajaxType: 'GET',
				title: '消息窗口',
				hasMask: false,
				dragable: true,
				buttons: null,					// 按钮集合 格式 [{id:'',name:'',call:null}] 
				showCall: null,
				closefunc: true,
				closeCall: null,
				width: 'auto',
				height: 'auto',
				position:{
					top: '0px',
					left: '0px',
					right: '0px',
					bottom: '0px'
				},
				opacity: .3,
				maskColor: '#000',
				padding: null,
				overflow: ['hidden', 'hidden']
		};
		this.config = $.extend({
			appendTo: top.document.body || document.body
		}, options, settings);
		this.mbox = getNodeHtml(this.config);
		this.mbox = setConfig(this.mbox, this.config);
		this.mbox = _modal(this.mbox, this.config);
		
		this.mbox.modal({show: true});
	}
	
});